package com.yixin.hospital.common;

import com.yixin.hospital.enums.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.MessageFormat;

@ControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public <T> ApiResult<T> handleException(MethodArgumentNotValidException e) {
        log.warn("参数校验异常：", e);
        FieldError fieldError = e.getBindingResult().getFieldError();
        String msg = fieldError == null ? "系统异常" : fieldError.getDefaultMessage();
        return ApiResult.error(msg);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> ApiResult<T> handleException(Exception e) {
        return ApiResult.error(e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public <T> ApiResult<T> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String errorMsg = MessageFormat.format(ResponseCodeEnum.PARAM_MUST_NOT_NULL.getMsg(), e.getParameterName());
        return ApiResult.error(ResponseCodeEnum.PARAM_MUST_NOT_NULL.getCode(), errorMsg);
    }
}
